#include"mystdio.h"
#include<string.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<unistd.h>

mFILE *mfopen(const char *filename, const char *mode)
{
  int fd=-1;
  if(strcmp(mode,"r")==0)
  {
   fd=open(filename,O_RDONLY);
  }

 else  if(strcmp(mode,"w")==0)
 {
   fd=open(filename,O_CREAT|O_WRONLY|O_TRUNC,0664);
 }
else if(strcmp(mode,"a")==0)
{
  fd=open(filename,O_CREAT|O_WRONLY|O_APPEND,0664);
}
if(fd<0)
{
  return NULL;
}
mFILE* fp=(mFILE*)malloc(sizeof(mFILE));
if(!fp)
{
  close(fd);
  return NULL;
}
fp->cap=SIZE;
fp->fileno=fd;
fp->size=0;
fp->flag=FLUSH_LINE;
return fp;
}
int mfwrite(const void *ptr, int num, mFILE *stream)
{
  if (stream->size + num > stream->cap)
  {
    mfflush(stream); // 缓冲区满，先刷新清空
  }
  memcpy(stream->outbuffer+stream->size,ptr,num);
  stream->size+=num;
  if(stream->flag==FLUSH_LINE&&stream->size>0&&stream->outbuffer[stream->size-1]=='\n')
  {
    mfflush(stream);
  }
  return num;
}
void mfflush(mFILE *stream)
{
  if(stream->size>0)
  {
    write(stream->fileno,stream->outbuffer,stream->size);
    fsync(stream->fileno);
    stream->size=0;
  }

}
void myclose(mFILE* stream)
{
  if(stream->size>0)
  {
    mfflush(stream);
  }
  close(stream->fileno);
}

